//
//  NSMutableAttributedString+UBBParser_m.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2019/4/23.
//  Copyright © 2019 CSDN. All rights reserved.
//

#import "NSMutableAttributedString+UBBParser_m.h"

@implementation NSMutableAttributedString (UBBParser_m)

- (void)enumUBBTag:(NSString *)ubbTag usingBlock:(void (^)(NSRange tagRange,
                                                           NSMutableAttributedString *tagContent,
                                                           NSMutableAttributedString *currentStr,
                                                           BOOL *stop))block
{
    NSString *reStr = [NSString stringWithFormat:@"\\[%@\\].*?\\[/%@\\]", ubbTag, ubbTag];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:reStr options:0 error:NULL];
    
    while (1) {
        NSTextCheckingResult *result = [regex firstMatchInString:self.mutableString options:0 range:NSMakeRange(0, self.length)];
        if (result == nil || result.range.location == NSNotFound) break;
        
        NSRange range = result.range;
        NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:[self.mutableString substringWithRange:range]];
        [content trimUBBTag:ubbTag];
        
        BOOL needStop = NO;
        block(range, content, self, &needStop);
        if (needStop) break;
    }
}

#pragma mark -

- (void)trimUBBTag:(NSString *)ubbTag
{
    NSString *endUBBTag = [NSString stringWithFormat:@"[/%@]", ubbTag];
    NSRange endRange = NSMakeRange(self.length - endUBBTag.length, endUBBTag.length);
    NSString *endSubStr = [self.mutableString substringWithRange:endRange];
    
    NSString *startUBBTag = [NSString stringWithFormat:@"[%@]", ubbTag];
    NSRange startRange = NSMakeRange(0, startUBBTag.length);
    NSString *startSubStr = [self.mutableString substringWithRange:startRange];
    
    if ([endSubStr isEqualToString:endUBBTag]) {
        [self replaceCharactersInRange:endRange withString:@""];
    }
    
    if ([startSubStr isEqualToString:startUBBTag]) {
        [self replaceCharactersInRange:startRange withString:@""];
    }
}

#pragma mark -
@end
